﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[ToolboxData("<{0}:MyGridView runat=server></{0}:MyGridView>")]
	public class MyGridView : GridView {
		private TableItemStyle m_pagerDigestStyle;

		/// <summary>
		/// 
		/// </summary>
		[Category("Styles")]
		[NotifyParentProperty(true)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		[Description("MyGridView_PagerDigestStyle")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public TableItemStyle PagerDigestStyle {
			get {
				if (this.m_pagerDigestStyle == null) {
					this.m_pagerDigestStyle = new TableItemStyle();
					if (base.IsTrackingViewState) {
						((IStateManager)this.m_pagerDigestStyle).TrackViewState();
					}
				}
				return this.m_pagerDigestStyle;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="row"></param>
		/// <param name="columnSpan"></param>
		/// <param name="pagedDataSource"></param>
		protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) {
			base.InitializePager(row, columnSpan, pagedDataSource);

			if (!AllowPaging)
				return;

			var cell = row.Cells[0];

			System.Diagnostics.Debug.Assert(cell != null);

			var itable = cell.Controls[0] as Table;
			if (itable == null)
				return;

			var firstIndex = pagedDataSource.CurrentPageIndex * pagedDataSource.PageSize + 1;
			var lastIndex = firstIndex + pagedDataSource.PageSize - 1;
			if (pagedDataSource.IsLastPage) {
				lastIndex = pagedDataSource.VirtualCount;
			}

			var irow = itable.Rows[0];
			var rcell = new TableCell();
			if (PagerDigestStyle != null) {
				rcell.MergeStyle(PagerDigestStyle);
			}
			rcell.Text = string.Format("({0}-{1}/{2})", firstIndex, lastIndex, pagedDataSource.VirtualCount);
			irow.Cells.Add(rcell);
		}
	} // end of MyGridView.
}
